#include "man_100.h"
#include "ui_man_100.h"
#include<QPainter>
#include<Qtimer>
#include<QKeyEvent>
man_100::man_100(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::man_100),Start(false),direction(-1),meet(false)
{
    ui->setupUi(this);
    this->setGeometry(QRect(900,380,290,310));
}

man_100::~man_100()
{
    delete ui;
}
void man_100::paintEvent(QPaintEvent *event){//绘画事件
    if(Start == false){
        Man();
    }
    QPainter painter(this);
    //游戏背景
    painter.setPen(Qt::black);
    painter.setBrush(Qt::gray);
    painter.drawRect(15,15,260,260);
    //画人
    painter.setPen(Qt::green);
    painter.setBrush(Qt::green);
    painter.drawRect(man);
    //画木块
    painter.setPen(Qt::green);
    painter.setBrush(Qt::green);
    painter.drawRect(Board);
}
void man_100::Man(){//人的初始化与活动
    Start=true;
    QRect rect(140,15,5,5);
    man=rect;
    timer = new QTimer(this);//计时器
    timer->start(350);//350ms
    connect(timer,SIGNAL(timeout()),SLOT(man_update()));
    time_cloud=new QTimer(this);
    time_cloud->start(350);
    connect(time_cloud,SIGNAL(timeout()),SLOT(cloud_update));
    Board = board();
}
void man_100::man_update(){//人的位置更新,同时木块上移,如果人踩在木块上，则一起上移
    if(man.top()-5==Board.top()&&man.left()==Board.left()){
        meet = true;
    }
    if(meet == false){
        switch(direction){
        case 0:
            man.setLeft(man.left()-5);
            man.setRight(man.right()-5);
            break;
        case 1:
            man.setLeft(man.left()+5);
            man.setRight(man.right()+5);
            break;
        default:;
        }
        man.setTop(man.top()+5);
        man.setBottom(man.bottom()+5);
        Board.setTop(Board.top()-5);
        Board.setBottom(Board.bottom()-5);
    }
    else{
        man.setTop(man.top()-5);
        man.setBottom(man.bottom()-5);
        Board.setTop(Board.top()-5);
        Board.setBottom(Board.bottom()-5);
    }
    update();//更新
}
void man_100::keyPressEvent(QKeyEvent *event){//人的键盘事件
    QKeyEvent *key=(QKeyEvent*) event;
    switch(key->key()){
    case Qt::Key_Left:
        direction = 0;
        break;
    case Qt::Key_Right:
        direction = 1;
        break;
    default :;
    }
}
QRect man_100::board(){
    int x;
    x=qrand()%50;
    QRect RECT(15+x*5,270,5,5);
    return RECT;
}
